package cn.zhl.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * @program: demos
 * @description:
 * @author: 刘振华
 * @create: 2020-04-27 19:26
 **/
public class ForkJoinDemo extends RecursiveTask<Long> {
	private Long start;
	private Long end;
	private Long sp = 10000L;

	public ForkJoinDemo(Long start, Long end) {
		this.start = start;
		this.end = end;
	}

	public static void main(String[] args) {
		ForkJoinDemo fj = new ForkJoinDemo(1L, 100000001L);
		ForkJoinPool pool = new ForkJoinPool();
		Long rs = pool.invoke(fj);
		System.out.println("=============================" + rs);
	}

	@Override
	protected Long compute() {
		System.out.println("start:" + start + ",end:" + end + ",ThreadName:" + Thread.currentThread().getName());
		long l = end - start;
		if (l > sp) {
			ForkJoinDemo left = new ForkJoinDemo(start, start + (l >> 1));
			ForkJoinDemo right = new ForkJoinDemo(start + (l >> 1), end);
			left.fork();
			right.fork();
			return left.join() + right.join();
		}
//        return LongStream.range(start,end).reduce(Long::sum).orElse(0L);
		return LongStream.range(start, end).sum();
	}
}
